package com.sheyu.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sheyu.common.utils.HttpUtils;
import com.sheyu.mall.member.dao.MemberLevelDao;
import com.sheyu.mall.member.entity.MemberLevelEntity;
import com.sheyu.mall.member.exception.PhoneException;
import com.sheyu.mall.member.exception.UsernameException;
import com.sheyu.mall.member.vo.MemberLoginVo;
import com.sheyu.mall.member.vo.MemberRegistVo;
import com.sheyu.mall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sheyu.common.utils.PageUtils;
import com.sheyu.common.utils.Query;

import com.sheyu.mall.member.dao.MemberDao;
import com.sheyu.mall.member.entity.MemberEntity;
import com.sheyu.mall.member.service.MemberService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveMemberRegist(MemberRegistVo memberRegistVo) {

        String username =  memberRegistVo.getUserName();
        String password = memberRegistVo.getPassword();
        String phone = memberRegistVo.getPhone();

        //检查用户与手机号是否有相同
        checkPhoneUnique(phone);
        checkUserNameUnique(username);

        MemberEntity memberEntity = new MemberEntity();
        //设置用户的基本信息
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setNickname(username);
        memberEntity.setUsername(username);

        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password);

        memberEntity.setPassword(encode);
        memberEntity.setMobile(phone);
        memberEntity.setCreateTime(new Date());

        //设置默认等级

        int insert = baseMapper.insert(memberEntity);
    }

    /**
     * 判断邮箱是否重复
     *
     * @param phone
     * @return
     */
    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer mobileCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (mobileCount>0){
            throw new PhoneException();
        }
    }

    /**
     * 判断用户名是否重复
     *
     * @param userName
     * @return
     */
    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (usernameCount>0){
            throw new UsernameException();
        }
    }

    /**
     * 用户登陆
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //去数据库查询用户名
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if(memberEntity==null){
            return null;
        }else{
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, passwordDb);
            if(matches){
                return memberEntity;
            }else{
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser){
        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid",uid));
        if (memberEntity != null){
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(memberEntity.getAccessToken());
            update.setExpiresIn(memberEntity.getExpiresIn());
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }else{
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            try {
                //3、查询当前社交用户的社交账号信息（昵称、性别等）
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");

                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setHeader(profileImageUrl);
                    register.setCreateTime(new Date());
                }
            }catch(Exception e){}

            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccess_token());
            register.setExpiresIn(socialUser.getExpires_in());

            //把用户信息插入到数据库中
            this.baseMapper.insert(register);


            return register;
        }
    }

}
